package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@WebFilter(filterName = "/*")
public class LoginFilter implements Filter {
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.资源放行
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        String requestURI = request.getRequestURI();
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if(match){
                chain.doFilter(req, resp);
                return;
            }
        }
        HttpSession session = request.getSession();
        Long employeeId = (Long) session.getAttribute("employee");
        User loginUser = (User) session.getAttribute("loginUser");
        if(employeeId !=null){
            BaseContext.setCurrentId(employeeId);
            chain.doFilter(req, resp);
            return;
        }
        if(loginUser!=null){
            BaseContext.setCurrentId(loginUser.getId());
            chain.doFilter(req, resp);
            return;
        }

        else {
            R<Object> error = R.error("NOTLOGIN");
            String s = JSON.toJSONString(error);
            response.getWriter().write(s);
        }
    }
}